import React, { useState, useEffect, useRef } from 'react'
import { Table, Button, Modal, Switch } from 'antd'

import {
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import axios from 'axios'
import UserForm from 'components/user-manage/UserForm'

const { confirm } = Modal

export default function RoleList() {
  const [dataSource, setDataSource] = useState([])
  const [roleList, setRoleList] = useState([])
  const [regionList, setRegionList] = useState([])
  const [isAddVisible, setIsAddVisible] = useState(false)
  const [isUpDateVisible, setIsUpDateVisible] = useState(false)
  const [isUpdateDisabled, setIsUpdateDisabled] = useState(false)
  const [current, setCurrent] = useState(null)
  const addForm = useRef(null)
  const updateForm = useRef(null)
  const { username, roleId, region } = JSON.parse(localStorage.getItem('token'))
  //   获取用户列表
  useEffect(() => {
    const roleObj = {
      1: 'superadmin',
      2: 'admin',
      3: 'editor',
    }
    axios.get('/users?_expand=role').then((res) => {
      // setDataSource(res.data)
      const list = res.data
      setDataSource(
        roleObj[roleId] === 'superadmin'
          ? list
          : [
              ...list.filter((item) => item.username === username),
              ...list.filter(
                (item) => item.region === region && roleObj[roleId] === 'editor'
              ),
            ]
      )
    })
  }, [username, roleId, region])
  // 获取区域列表
  useEffect(() => {
    axios.get('/regions').then((res) => {
      setRegionList(res.data)
    })
  }, [])

  // 获取角色列表
  useEffect(() => {
    axios.get('/roles').then((res) => {
      setRoleList(res.data)
    })
  }, [])

  const showDeleteConfirm = (item) => {
    confirm({
      title: '是否确认删除?',
      icon: <ExclamationCircleOutlined />,
      okText: 'Yes',
      okType: 'danger',
      cancelText: 'No',
      onOk() {
        deleteMethod(item)
      },
      onCancel() {},
    })
  }

  //   确认删除的方法
  const deleteMethod = (item) => {
    setDataSource(dataSource.filter((ele) => ele.id !== item.id))
    axios.delete(`/users/${item.id}`)
  }

  const handleChange = (item) => {
    item.roleState = !item.roleState
    setDataSource([...dataSource])
    axios.patch(`/users/${item.id}`, {
      roleState: item.roleState,
    })
  }

  // 更新用户的方法
  const handleUpDate = (item) => {
    setTimeout(() => {
      setIsUpDateVisible(true) //状态的更新是异步操作
      if (item.roleId === 1) {
        setIsUpdateDisabled(true)
      } else {
        setIsUpdateDisabled(false)
      }

      updateForm.current.setFieldsValue(item)
    }, 0)
    setCurrent(item)
  }

  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      render: (region) => {
        return <b>{region ? region : '全球'}</b>
      },
      filters: [
        ...regionList.map((item) => ({
          text: item.title,
          value: item.value,
        })),
        {
          text: '全球',
          value: '全球',
        },
      ],
      onFilter: (value, item) => {
        if (value === '全球') {
          return item.region === ''
        }
        return item.region === value
      },
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      render: (role) => {
        return role?.roleName
      },
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '用户状态',
      dataIndex: 'roleState',
      render: (roleState, item) => {
        return (
          <Switch
            checked={roleState}
            disabled={item.default}
            onChange={() => handleChange(item)}
          ></Switch>
        )
      },
    },
    {
      title: '操作',
      render: (item) => {
        return (
          <div>
            <Button
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              disabled={item.default}
              onClick={() => showDeleteConfirm(item)}
            />
            <Button
              onClick={() => handleUpDate(item)}
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              disabled={item.default}
            />
          </div>
        )
      },
    },
  ]

  return (
    <div>
      <Button type="primary" onClick={() => setIsAddVisible(true)}>
        添加用户
      </Button>
      <Table
        columns={columns}
        dataSource={dataSource}
        rowKey={(item) => item.id} //缺少key属性报错使用rowKey返回函数 或是字符串
        pagination={{
          pageSize: 5,
        }}
      />

      {/* 添加用户的模态框 */}
      <Modal
        visible={isAddVisible}
        title="添加用户"
        okText="确认"
        cancelText="取消"
        onCancel={() => setIsAddVisible(false)}
        onOk={() => {
          addForm.current
            .validateFields()
            .then((values) => {
              setIsAddVisible(false)
              addForm.current.resetFields()
              axios
                .post(`/users`, {
                  ...values,
                  roleState: true,
                  default: false,
                })
                .then((res) => {
                  setDataSource([
                    ...dataSource,
                    {
                      ...res.data,
                      role: roleList.filter(
                        (item) => item.id === values.roleId
                      )[0],
                    },
                  ])
                })
            })
            .catch((info) => {
              console.log(info)
            })
          setIsAddVisible(false)
        }}
      >
        <UserForm ref={addForm} regionList={regionList} roleList={roleList} />
      </Modal>

      {/* 更新用户的模态框 */}
      <Modal
        visible={isUpDateVisible}
        title="更新用户"
        okText="更新"
        cancelText="取消"
        onCancel={() => {
          setIsUpDateVisible(false)
          setIsUpdateDisabled(!isUpdateDisabled)
        }}
        onOk={() => {
          updateForm.current
            .validateFields()
            .then((values) => {
              setIsUpDateVisible(false)
              setDataSource(
                dataSource.map((item) => {
                  if (item.id === current.id) {
                    return {
                      ...item,
                      ...values,
                      role: roleList.filter(
                        (data) => data.id === values.roleId
                      )[0],
                    }
                  }

                  return item
                })
              )
              setIsUpdateDisabled(!isUpdateDisabled)
              axios.patch(`/users/${current.id}`, values)
            })
            .catch((info) => {
              console.log(info)
            })
          setIsUpDateVisible(false)
        }}
      >
        <UserForm
          isUpdate={true}
          ref={updateForm}
          regionList={regionList}
          roleList={roleList}
          isUpdateDisabled={isUpdateDisabled}
        />
      </Modal>
    </div>
  )
}
